package org.demo.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.demo.dao.model.Article;
import org.demo.service.article.ArticleService;
import org.demo.util.ElasticSearchUtil;
import org.demo.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

@Controller
@RequestMapping("article")
public class ArticleController {

	@Autowired
	private ArticleService articleService;
	
	@RequestMapping("index")
	public String index() {
		return "article/index"; 
	}

	@RequestMapping(value="save",method=RequestMethod.GET)
	public String init() {
		return "article/save";
	}

	@RequestMapping(value="save",method=RequestMethod.POST)
	public String save(Article article) {
		article.setId(Math.abs(UUID.randomUUID().hashCode()));
		article.setCreateTime(new Date());
		articleService.save(article);
		ElasticSearchUtil util = new ElasticSearchUtil("article-2017.07.07", "articles", null);
		util.addIndex(Article.class, article);
		return "redirect:/article/search";
	}
	
	@RequestMapping("search")
	@ResponseBody
	public Page search(String wd, Integer pageNo, Integer pageSize) {
		ElasticSearchUtil util = new ElasticSearchUtil("article-2017.07.07", "articles");
		Page page = util.getListBySearch(wd, pageNo, pageSize, true, Article.class, "title","content");
		return page;
	}
	
	@RequestMapping("details/{id}")
	public String details(@PathVariable("id") String id,HttpServletRequest request) {
		return "article/details";
	}
	
	@RequestMapping("details")
	@ResponseBody
	public Object details(@RequestParam(required=true) String id) {
		ElasticSearchUtil util = new ElasticSearchUtil();
		return util.getDetails(Article.class);
	}
}
